<?php
require_once ('..'.DIRECTORY_SEPARATOR.'initialize.php');
//GET Request
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    include_once(Utils::getPath(array('shared', 'template.php')));
    include_once(Utils::getPath(array('repositories', 'userRepository.php')));
    include_once(Utils::getPath(array('repositories', 'messageRepository.php')));

    $template = new Template('application');
    $template->initialize();

    $userRep = new UserRepository();
    if (isset($_SESSION['newmsgform']))
        $newmsgform = $_SESSION['newmsgform'];

    if (isset($_GET['reply'])) {
        $messageRep = new MessageRepository();
        $msg = $messageRep->getById($_GET['reply']);

        if (!isset($msg)) {
            Utils::goToErrorPage(StatusCodes::HTTP_BAD_REQUEST);
        }

        $receiver = $msg->getIdReceiver();
        $sender = $msg->getIdSender();
        $subject = $msg->getSubject();
        $date = $msg->getDate();
        $text = $msg->getText();

        if (isset($_GET['reply']) && $receiver == $_SESSION['authenticatedId']) {
            $newmsgform['receiver'] = $userRep->getById($sender)->getUserName();
            $newmsgform['subject'] = 'Re: ' . $subject;
        } else if (isset($_GET['foward']) && ($receiver == $_SESSION['authenticatedId'] || $sender == $_SESSION['authenticatedId'])) {
            $newmsgform['receiver'] = '';
            $newmsgform['subject'] = 'Fwd: ' . $subject;
            $newmsgform['text'] = $text;
        } else {
            Utils::goToErrorPage(StatusCodes::HTTP_BAD_REQUEST);
        }
    } else if (isset($_GET['id'])) {
        $receiverUser = $userRep->getById($_GET['id']);
        if(!isset($receiverUser)){
            Utils::goToErrorPage();
        }
        $newmsgform['receiver'] = $receiverUser->getUserName($receiverUser);
        $newmsgform['subject'] = '';
        $newmsgform['text'] = '';
    }else{
        Utils::goToErrorPage();
    }
    ?>
    <h2>New message</h2>
    <form id="newMsg-form" action="new.php" method="post" enctype="multipart/form-data">
        <div class="form-element">
            <label for="receiver">Receiver</label>
                <input type="text" name="receiver" readonly="readonly" value="<?php if (isset($newmsgform['receiver']))
        echo $newmsgform['receiver']; ?>" maxlength="32"/>
        </div>

        <div class="form-element">
            <label for="subject">Subject</label>
                <input type="text" name="subject" value="<?php if (isset($newmsgform['subject']))
        echo $newmsgform['subject']; ?>" onkeypress="return imposeMaxLength(this, 256);" />
        </div>

        <div class="form-element">
            <label for="text">Text</label>
                <textarea name="text" onkeypress="return imposeMaxLength(this, 1024);" rows="8" cols="64" ><?php if (isset($newmsgform['text']))
        echo $newmsgform['text']; ?></textarea>
        </div>
        
        <div class="submit">
            <input type="submit" value="Send"/>
        </div>

    </form>
    <?php
    $template->createPage('New message');
}
//POST Request
else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    include_once(Utils::getPath(array('repositories', 'userRepository.php')));
    include_once(Utils::getPath(array('repositories', 'messageRepository.php')));

    foreach ($_POST as $key => $value) {
        $_SESSION['newmsgform'][$key] = $value;
    }
    $newmsgform = & $_SESSION['newmsgform'];

    //Data check
    $sender = $_SESSION['authenticatedId'];
    $receiver = $_REQUEST['receiver'];
    $subject = htmlspecialchars($_REQUEST['subject']);
    $text = htmlspecialchars($_REQUEST['text']);

    $errorList = array();

    if (!isset($receiver) || $receiver == '') {
        $errorList[] = 'Empty receiver';
    } else {
        //Search user in database
        $userRep = new UserRepository();
        $user = $userRep->findByUserName($receiver);
        if (is_null($user)) {
            $errorList[] = 'The specified receiver does not exist';
            $newmsgform['receiver'] = '';
        } else if ($user->getId() == $_SESSION['authenticatedId']) {
            $errorList[] = "You can\'t send messages to yourself";
            $newmsgform['receiver'] = '';
        } else {
            $receiver = $user->getId();
        }
    }

    if (!isset($subject) || $subject == '') {
        $errorList[] = 'Empty subject';
    } else if (strlen($subject) > 256) {
        $errorList[] = 'The maximum size of the subject is 256 characters';
    }

    if (!isset($text) || $text == '') {
        $errorList[] = 'Empty text';
    } else if (strlen($text) > 1024) {
        $errorList[] = 'The maximum size of the text is 1024 characters';
    }

    //Check for errors
    if ($errorList) {
        Utils::showErrorList($errorList);
        header("Location: new.php");
        exit();
    }

    //Everything is ok, so we can send message	

    $_SESSION['newmsgform'] = null;

    $message = new Message();
    $message->setIdReceiver($receiver);
    $message->setIdSender($sender);
    $message->setSubject($subject);
    $message->setText($text);

    $messageRepository = new MessageRepository();
    $message = $messageRepository->persist($message);

    Utils::showInfo('Success!');
    header("Location: list.php");
    exit();
}
?>